package threadDemo;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author macpro
 * @date 2019-07-13
 * @function  顺序打印
 *
 * 当前lock condition await 后已经准备就绪的 thread 才可以抢线程。
 *
 */
public class ReentrantThreadPrintByOrder {
    public static void main(String[] args) {
        new ReentrantThreadPrintByOrder().alternateTask();
    }
    private void alternateTask() {
        ReentrantLock lock = new ReentrantLock();
        Condition condition1 = lock.newCondition();
        Condition condition2 = lock.newCondition();
        Condition condition3 = lock.newCondition();
        Thread thread1 = new Thread(() -> {
            try {
                lock.lock();
                for (int i = 65; i < 91; i++) {
                    System.out.println("----------thread1------- " + (char) i+" "+System.currentTimeMillis());
                    condition2.signal();
//                    Thread.sleep(2000);
                    System.out.println("----------thread1 await ------- " + (char) i+" "+System.currentTimeMillis());
                    condition1.await();
                }
                condition2.signal();
            } catch (Exception e) {
            } finally {
                System.out.println("thread1 finally");
                lock.unlock();
            }
        });
        Thread thread2 = new Thread(() -> {
            try {
                lock.lock();
                for (int i = 0; i < 26; i++) {
                    System.out.println("----------thread2------- " + i+" "+System.currentTimeMillis());
                    condition3.signal();
//                    Thread.sleep(1000);
                    System.out.println("----------thread2 await------- " + i+" "+System.currentTimeMillis());
                    condition2.await();
                }
                condition3.signal();
            } catch (Exception e) {
            } finally {
                System.out.println("thread2 finally");
                lock.unlock();
            }
        });

        Thread thread3 = new Thread(() -> {
            try {
                lock.lock();
                for (int i = 100; i < 126; i++) {
                    System.out.println("----------thread3------- " + i+" "+System.currentTimeMillis());
                    condition1.signal();
//                    Thread.sleep(1000);
                    System.out.println("----------thread3 await------- " + i+" "+System.currentTimeMillis());
                    condition3.await();
                }
                condition1.signal();
            } catch (Exception e) {
            } finally {
                System.out.println("thread3 finally");
                lock.unlock();
            }
        });
        thread1.start();
        thread2.start();
        thread3.start();
    }


}
